<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
			<el-form-item label="名称" prop="deptName">
				<el-input v-model="queryParams.deptName" placeholder="请输入名称" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="状态" prop="status">
				<el-select v-model="queryParams.status" placeholder="状态" clearable>
					<el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
						:value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
				<el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>

			</el-form-item>
		</el-form>

		<!--  <el-row :gutter="10" class="mb8">
     <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:dept:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

		<el-table v-if="refreshTable" v-loading="loading" :data="deptList" row-key="deptId"
			:default-expand-all="isExpandAll" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
			<el-table-column prop="deptName" label="名称" width="260"></el-table-column>
			<el-table-column prop="orderNum" label="排序" width="200"></el-table-column>
			<el-table-column prop="status" label="状态" width="100">
				<template slot-scope="scope">
					<dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
				</template>
			</el-table-column>
			<!-- <el-table-column prop="type" label="类型" width="100">
				<template slot-scope="scope">
					<dict-tag :options="dict.type.dept_type" :value="scope.row.type" />
				</template>
			</el-table-column> -->
			<!-- <el-table-column prop="localtionName" label="地址" width="260"></el-table-column> -->
			<el-table-column label="创建时间" align="center" prop="createTime" width="200">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.createTime) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button v-if="scope.row.parentId != 0" size="mini" type="text" icon="el-icon-edit"
						@click="handleUpdate(scope.row)" v-hasPermi="['system:dept:edit']">修改</el-button>
					<el-button v-if="scope.row.parentId == 0" size="mini" type="text" icon="el-icon-plus"
						@click="handleAdd(scope.row)" v-hasPermi="['system:dept:add']">新增</el-button>
					<el-button v-if="scope.row.parentId != 0" size="mini" type="text" icon="el-icon-delete"
						@click="handleDelete(scope.row)" v-hasPermi="['system:dept:remove']">删除</el-button>
					<el-button v-if="scope.row.parentId == 0" size="mini" type="text" icon="el-icon-setting"
						@click="handleSettings(scope.row)" v-hasPermi="['system:dept:edit']">设置</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 添加或修改信息对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-row>
					<el-col :span="24" v-if="form.parentId !== 0">
						<el-form-item label="上级信息" prop="parentId">
							<treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer"
								placeholder="选择上级信息" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
		<!-- 			<el-col :span="12">
						<el-form-item label="类型" prop="type">
							<el-radio v-model="form.type" v-if="groupFlag1" label="1">代理商</el-radio>
							<el-radio v-model="form.type" v-if="groupFlag2" label="2">校区</el-radio>
							<el-radio v-model="form.type" v-if="groupFlag3" label="3">楼栋</el-radio>
						</el-form-item>
					</el-col> -->
					<el-col :span="12">
						<el-form-item label="状态">
							<el-radio-group v-model="form.status">
								<el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
									:label="dict.value">{{dict.label}}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="名称" prop="deptName">
							<el-input v-model="form.deptName" placeholder="请输入名称" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="显示排序" prop="orderNum">
							<el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
						</el-form-item>
					</el-col>
				</el-row>
		<!-- 		<el-row>
					<el-col :span="24" v-if="form.type == 2">
						<el-form-item label="地址信息" prop="name" :key="nameKey">
							<!-- <el-input v-model="form.name" placeholder="请输入地址信息" />
							<el-select v-model="form.name" filterable remote reserve-keyword placeholder="请输入关键词"
								style="width: 100%;" :remote-method="remoteMethod" :loading="loadingSe"
								:clearable="true" @change="currentSelect">
								<el-option v-for="item in options" :key="item.id" :label="item.name" :value="item"
									class="one-text">
									<span style="float: left">{{ item.name }}</span>
									<span
										style="float: right; color: #8492a6; font-size: 13px">{{ item.district }}</span>
								</el-option>
							</el-select>
						</el-form-item>
						<gaode-map @confirm="closeModal" @remoteMethodBack="remoteMethodBack" ref="gaodeMap" />
					</el-col>
				</el-row> -->
				<!--        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row> -->
				<!-- <el-row> -->
				<!--    <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col> -->

				<!-- </el-row> -->
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 系统配置对话框 -->
		<el-dialog :title="'系统配置 - ' + settingsForm.deptName" :visible.sync="settingsOpen" width="700px" append-to-body>
			<el-form ref="settingsForm" :model="settingsForm" label-width="120px">
				<el-tabs v-model="activeTab">
					<el-tab-pane label="基础设置" name="basic">
						<el-row>
							<el-col :span="12">
								<el-form-item label="系统名称">
									<el-input v-model="settingsForm.systemName" placeholder="请输入系统名称" />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="系统简称">
									<el-input v-model="settingsForm.systemShortName" placeholder="请输入系统简称" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="系统描述">
									<el-input type="textarea" v-model="settingsForm.systemDescription" :rows="2" placeholder="请输入系统描述" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="版权信息">
									<el-input v-model="settingsForm.copyright" placeholder="请输入版权信息" />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="备案号">
									<el-input v-model="settingsForm.icp" placeholder="请输入备案号" />
								</el-form-item>
							</el-col>
						</el-row>
					</el-tab-pane>

					<el-tab-pane label="界面设置" name="ui">
						<el-row>
							<el-col :span="24">
								<el-form-item label="系统Logo">
									<el-upload
										class="avatar-uploader"
										action="#"
										:http-request="uploadLogo"
										:show-file-list="false"
										:before-upload="beforeLogoUpload">
										<img v-if="settingsForm.logoUrl" :src="settingsForm.logoUrl" class="avatar">
										<i v-else class="el-icon-plus avatar-uploader-icon"></i>
										<div class="el-upload__tip" slot="tip">建议上传尺寸: 120px * 120px，支持jpg、png格式</div>
									</el-upload>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="登录背景">
									<el-upload
										class="bg-uploader"
										action="#"
										:http-request="uploadBackground"
										:show-file-list="false"
										:before-upload="beforeBackgroundUpload">
										<img v-if="settingsForm.backgroundUrl" :src="settingsForm.backgroundUrl" class="bg-image">
										<i v-else class="el-icon-plus bg-uploader-icon"></i>
										<div class="el-upload__tip" slot="tip">建议上传尺寸: 1920px * 1080px，支持jpg、png格式</div>
									</el-upload>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="主题色">
									<el-color-picker v-model="settingsForm.primaryColor" show-alpha></el-color-picker>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="登录页标语">
									<el-input v-model="settingsForm.loginSlogan" placeholder="请输入登录页标语" />
								</el-form-item>
							</el-col>
						</el-row>
					</el-tab-pane>
				</el-tabs>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitSettings">确 定</el-button>
				<el-button @click="cancelSettings">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	// import gaodeMap from "./gaodeMap.vue";
	import {
		listDept,
		getDept,
		delDept,
		addDept,
		updateDept,
		listDeptExcludeChild
	} from "@/api/system/dept";

	import Treeselect from "@riophae/vue-treeselect";
	import "@riophae/vue-treeselect/dist/vue-treeselect.css";

	export default {
		name: "Dept",
		dicts: ['sys_normal_disable', 'dept_type'],
		components: {
			Treeselect
		},
		data() {
			return {
				groupFlag1: false,
				groupFlag2: false,
				groupFlag3: false,
				appidList: [],
				loadingSe: false,
				// 遮罩层
				loading: true,
				// 显示搜索条件
				showSearch: true,
				// 表格树数据
				deptList: [],
				// 新增信息树选项
				deptOptions: [],
				options: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 系统配置弹出层
				settingsOpen: false,
				// 系统配置标签页
				activeTab: 'basic',
				// 系统配置表单
				settingsForm: {
					deptId: undefined,
					deptName: '',
					// 基础设置
					systemName: '智能门禁管理系统',
					systemShortName: '门禁管理',
					systemDescription: '',
					copyright: 'Copyright © 2023 Company All Rights Reserved.',
					icp: '',
					// 界面设置
					logoUrl: '',
					backgroundUrl: '',
					primaryColor: '#409EFF',
					loginSlogan: '欢迎登录智能门禁管理系统',
					remark: ''
				},
				// 是否展开，默认全部展开
				isExpandAll: true,
				// 重新渲染表格状态
				refreshTable: true,
				// 查询参数
				queryParams: {
					deptName: undefined,
					status: undefined
				},
				// 表单参数
				form: {


				},
				nameKey: 1,
				formKey: 2,
				// 表单校验
				rules: {
					parentId: [{
						required: true,
						message: "上级信息不能为空",
						trigger: "blur"
					}],
					deptName: [{
						required: true,
						message: "名称不能为空",
						trigger: "blur"
					}],
					orderNum: [{
						required: true,
						message: "显示排序不能为空",
						trigger: "blur"
					}],
					email: [{
						type: "email",
						message: "请输入正确的邮箱地址",
						trigger: ["blur", "change"]
					}],
					phone: [{
						pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
						message: "请输入正确的手机号码",
						trigger: "blur"
					}]
				}
			};
		},
		created() {
			// this.getAppIdList();

			this.getList();
		},
		methods: {
			closeModal(param) {
				// Commented out to prevent gaodeMap initialization issues
				/*
				this.form.name = param.address
				this.form.longitude = param.lng
				this.form.latitude = param.lat
				this.formKey += 1;
				this.nameKey = param.adcode;
				*/
			},
			remoteMethod(query) {
				// Commented out to prevent gaodeMap initialization issues
				/*
				this.$nextTick(() => {
					this.loadingSe = true
					this.$refs.gaodeMap.remoteMethod(query);
				});
				*/
			},
			remoteMethodBack(data) {
				// Commented out to prevent gaodeMap initialization issues
				/*
				this.loadingSe = false
				this.options = data
				*/
			},
			currentSelect(val) {
				// Commented out to prevent gaodeMap initialization issues
				/*
				this.$nextTick(() => {
					this.$refs.gaodeMap.currentSelect(val);
				});
				*/
			},
			/** 查询新增信息列表 */
			getList() {
				this.loading = true;
				listDept(this.queryParams).then(response => {
					this.deptList = this.handleTree(response.data, "deptId");
					// 处理结果，最多显示两级
					this.deptList.forEach(dept => {
						if (dept.children && dept.children.length > 0) {
							dept.children.forEach(child => {
								// 移除第三级及以下的部门
								if (child.children) {
									delete child.children;
								}
							});
						}
					});
					console.log("输出了deptList：",this.deptList)
					this.loading = false;
				});
			},
			/* 校区 */
			getAppIdList() {
				listAddress2(this.queryParams).then(response => {
					const addressList = response.rows;
					this.appidList = addressList.map(address => {
						return {
							label: address.name,
							value: address.id
						}
					})
				});
			},
			/** 转换新增信息数据结构 */
			normalizer(node) {
				if (node.children && !node.children.length) {
					delete node.children;
				}
				return {
					id: node.deptId,
					label: node.deptName,
					children: node.children
				};
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					deptId: undefined,
					parentId: undefined,
					deptName: undefined,
					orderNum: undefined,
					leader: undefined,
					phone: undefined,
					email: undefined,
					status: "0"
				};
				this.resetForm("form");
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			/** 新增按钮操作 */
			handleAdd(row) {
				this.reset();
				if (row != undefined) {
					this.form.parentId = row.deptId;
				}
				this.open = true;
				this.title = "添加新增信息";
				listDept().then(response => {
					// 只显示顶级部门作为父部门选项
					const filteredData = response.data.filter(item => item.parentId == 0);
					this.deptOptions = this.handleTree(filteredData, "deptId");
				});
			},
			/** 展开/折叠操作 */
			toggleExpandAll() {
				this.refreshTable = false;
				this.isExpandAll = !this.isExpandAll;
				this.$nextTick(() => {
					this.refreshTable = true;
				});
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				getDept(row.deptId).then(response => {
					if (response.data.longitude) {
						this.form = {
							...response.data,
							lng: response.data.longitude,
							lat: response.data.latitude
						}
					} else {
						this.form = response.data;
					}
					this.open = true;
					this.title = "修改信息";

					// 移除高德地图初始化，防止UI出现问题
					// this.$nextTick(() => {
					//	this.$refs.gaodeMap.initMap(this.form);
					// });

					// 修改时，只能选择顶级部门作为父部门
					listDept().then(response => {
						// 仅显示顶级部门
						const filteredData = response.data.filter(item => item.parentId == 0);
						this.deptOptions = this.handleTree(filteredData, "deptId");

						// 如果当前部门的父部门不在筛选后的列表中，添加它
						if (this.form.parentId != 0) {
							const parentExists = filteredData.some(item => item.deptId === this.form.parentId);
							if (!parentExists) {
								const parentInfo = {
									deptId: this.form.parentId,
									deptName: this.form.parentName || '上级部门',
									children: []
								};
								this.deptOptions.push(parentInfo);
							}
						}
					});
				});
			},
			/** 提交按钮 */
			submitForm: function() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.form.deptId != undefined) {
							updateDept(this.form).then(response => {
								this.$modal.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							addDept(this.form).then(response => {
								this.$modal.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				this.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项？').then(function() {
					return delDept(row.deptId);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			/** 设置按钮操作 */
			handleSettings(row) {
				this.settingsForm = {
					deptId: row.deptId,
					deptName: row.deptName,
					// 基础设置
					systemName: '智能门禁管理系统',
					systemShortName: '门禁管理',
					systemDescription: '',
					copyright: 'Copyright © 2023 Company All Rights Reserved.',
					icp: '',
					// 界面设置
					logoUrl: '',
					backgroundUrl: '',
					primaryColor: '#409EFF',
					loginSlogan: '欢迎登录智能门禁管理系统',
					remark: ''
				};

				// 这里可以添加获取当前部门配置信息的接口调用
				// getSystemConfig(row.deptId).then(response => {
				//   if (response.data) {
				//     this.settingsForm = { ...this.settingsForm, ...response.data };
				//   }
				// });

				this.settingsOpen = true;
			},

			/** Logo上传前检查 */
			beforeLogoUpload(file) {
				const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPGOrPNG) {
					this.$message.error('上传Logo只能是JPG或PNG格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传Logo大小不能超过2MB!');
				}
				return isJPGOrPNG && isLt2M;
			},

			/** 上传Logo */
			uploadLogo(options) {
				const file = options.file;
				// 模拟上传
				const reader = new FileReader();
				reader.readAsDataURL(file);
				reader.onload = () => {
					this.settingsForm.logoUrl = reader.result;
				};

				// 实际上传代码
				// const formData = new FormData();
				// formData.append('file', file);
				// uploadFile(formData).then(response => {
				//   this.settingsForm.logoUrl = response.data.url;
				// });
			},

			/** 背景图上传前检查 */
			beforeBackgroundUpload(file) {
				const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
				const isLt5M = file.size / 1024 / 1024 < 5;

				if (!isJPGOrPNG) {
					this.$message.error('上传背景图只能是JPG或PNG格式!');
				}
				if (!isLt5M) {
					this.$message.error('上传背景图大小不能超过5MB!');
				}
				return isJPGOrPNG && isLt5M;
			},

			/** 上传背景图 */
			uploadBackground(options) {
				const file = options.file;
				// 模拟上传
				const reader = new FileReader();
				reader.readAsDataURL(file);
				reader.onload = () => {
					this.settingsForm.backgroundUrl = reader.result;
				};

				// 实际上传代码
				// const formData = new FormData();
				// formData.append('file', file);
				// uploadFile(formData).then(response => {
				//   this.settingsForm.backgroundUrl = response.data.url;
				// });
			},

			/** 取消系统设置 */
			cancelSettings() {
				this.settingsOpen = false;
			},

			/** 提交系统设置 */
			submitSettings() {
				// 这里可以添加保存配置的接口调用
				// saveSystemConfig(this.settingsForm).then(response => {
				//   this.$modal.msgSuccess("保存成功");
				//   this.settingsOpen = false;
				// });

				// 临时提示
				this.$modal.msgSuccess("保存成功");
				this.settingsOpen = false;
			}
		}
	};
</script>

<style scoped>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409EFF;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 120px;
	height: 120px;
	line-height: 120px;
	text-align: center;
}
.avatar {
	width: 120px;
	height: 120px;
	display: block;
}
.bg-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.bg-uploader .el-upload:hover {
	border-color: #409EFF;
}
.bg-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 240px;
	height: 135px;
	line-height: 135px;
	text-align: center;
}
.bg-image {
	width: 240px;
	height: 135px;
	display: block;
}
.form-tip {
	font-size: 12px;
	color: #909399;
	margin-left: 5px;
}
</style>
